package com.atguigu.lease.web.app.service.impl;


import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.atguigu.lease.common.constant.RedisConstant;
import com.atguigu.lease.common.exceptions.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.web.app.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.cache.CacheProperties;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Random;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private Client client;
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public void sendCode(String phone) throws Exception {

        String key = RedisConstant.APP_LOGIN_PREFIX +phone;

        //0. 检查手机验证码是否失效
        //方案1： 验证码有效期和redis存储一致
//        Boolean is = redisTemplate.hasKey(key);
//        if (is) {
//            throw new LeaseException(ResultCodeEnum.APP_SEND_SMS_TOO_OFTEN);
//        }
        //方案2： 验证码的有效期和redis的存储不一致 600 可以二次发送的间隔是60
        Boolean is = redisTemplate.hasKey(key);
        if (is){
            //剩余的有效时间
            Long expire = redisTemplate.getExpire(key, TimeUnit.SECONDS);
            //  总有效时间 600 - 获取redis中key剩余的有效时间 539 < 间隔时间 60 不可以发送
            if (RedisConstant.APP_LOGIN_CODE_TTL_SEC - expire < RedisConstant.APP_LOGIN_CODE_RESEND_TIME_SEC){
                //没到间隔 不能发送
                throw new LeaseException(ResultCodeEnum.APP_SEND_SMS_TOO_OFTEN);
            }
        }

        //1.生成一个随机的验证码数字（4位）
        Random random = new Random();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 4 ; i++) {
            int number = random.nextInt(10);
            sb.append(number);
        }
        String code = sb.toString();

        //2.阿里短信验证发送验证码
        SendSmsRequest smsRequest = new SendSmsRequest();
        smsRequest.setPhoneNumbers(phone);
        smsRequest.setSignName("阿里云短信测试");
        smsRequest.setTemplateCode("SMS_154950909");
        smsRequest.setTemplateParam("{\"code\":\"" + code + "\"}\n");
        client.sendSms(smsRequest);
        //3.将验证码存储到redis中，使用手机号作为key

        redisTemplate.opsForValue().set(key,code,RedisConstant.APP_LOGIN_CODE_TTL_SEC, TimeUnit.SECONDS);
    }
}
